package me.wangxuan.pat.dao;

import java.util.List;
import java.util.Optional;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import me.wangxuan.pat.JpaConfig;
import me.wangxuan.pat.entity.Project;

public class ProjectDao {
	private EntityManagerFactory emf = JpaConfig.getEntityManagerFactory();

	public void create(Project p) {
		EntityManager em = emf.createEntityManager();
		EntityTransaction tx = em.getTransaction();
		try {
			tx.begin();
			em.persist(p);
			tx.commit();
		} catch (Exception e) {
			if (tx.isActive()) {
				tx.rollback();
			}
			throw e;
		} finally {
			em.close();
		}
	}
	
	public List<Project> findAll() {
		EntityManager em = emf.createEntityManager();
//        try {
//            return em.createQuery("FROM Item", Project.class).getResultList();
//        } finally {
//            em.close();
//        }
        
        // 使用 Criteria API 查询所有用户
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Project> cq = cb.createQuery(Project.class);
        Root<Project> userRoot = cq.from(Project.class);
        cq.select(userRoot);

        TypedQuery<Project> query = em.createQuery(cq);
        return query.getResultList();
        
	}
	
	public Optional<Project> findById(Integer id) {
		EntityManager em = emf.createEntityManager();
        return Optional.ofNullable(em.find(Project.class, id));
    }
}
